package cn.bisoft.java.util.common;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class DumpUtil {

	private static XStream XSTREAM = new XStream(new DomDriver());

	public static String object2XML(Object obj, String outFileName)
			throws FileNotFoundException {
		File outFile = new File(outFileName);
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(outFile));
		XMLEncoder xmlEncoder = new XMLEncoder(bos);
		xmlEncoder.writeObject(obj);
		xmlEncoder.close();

		return outFile.getAbsolutePath();
	}

	public static Object xml2Object(String inFileName)
			throws FileNotFoundException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				inFileName));
		XMLDecoder xmlDecoder = new XMLDecoder(bis);
		Object obj = xmlDecoder.readObject();
		xmlDecoder.close();

		return obj;
	}

	public synchronized static String toXML(Object o) {
		XSTREAM.alias(o.getClass().getSimpleName(), o.getClass());

		return XSTREAM.toXML(o);
	}

	public synchronized static Object fromXML(String xml) {
		return XSTREAM.fromXML(xml);
	}

}
